# 修改后的主程序
import logging
import traceback
from datetime import datetime
from pathlib import Path

from PyQt6.QtWidgets import QApplication, QMainWindow, QFileDialog, QMessageBox
from PyQt6.QtCore import QPropertyAnimation, QEasingCurve
from qdarkstyle import load_stylesheet, LightPalette, DarkPalette
from UI.UI_mainWindow import Ui_MainWindow
from logger import QtLogger
from data_process import ProcessThread


class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.data_map = {}
        self.now_year = 2025
        self.mode = 0
        self.base_week = 200001
        self.comparison_week = 200002
        self.is_data_checked = False
        self.setupUi(self)

        # 初始化日志模块
        self.logger = QtLogger(self.textBrowser, level=logging.DEBUG)  # 传入textBrowser控件

        # 测试日志输出
        self.log = self.logger.get_logger(__name__)
        self._init_signals()
        self._init_settings()
        self.log.debug("Debug information")
        self.log.info("System initialization completed.")

    def _init_signals(self):
        self.pushButton.clicked.connect(self.select_input_directory)
        self.pushButton_2.clicked.connect(self.select_output_directory)
        self.pushButton_3.clicked.connect(self.check_input_files)
        self.pushButton_4.clicked.connect(self.start_process)
        self.pushButton_5.clicked.connect(self.on_clear_logs)

        self.comboBox.currentIndexChanged.connect(self.update_controls_state)
        self.comboBox_2.currentIndexChanged.connect(self.on_change_log_level)

    def _init_settings(self):
        self.textBrowser.setStyleSheet("background-color: #1b1b1b; color: #ffffff;")
        self.now_year = datetime.now().year
        self.now_week = datetime.now().isocalendar()[1]
        self.dateEdit.setDate(datetime.now())
        base_week = self.now_week - 2 if self.now_week > 2 else self.now_week
        self.spinBox.setValue(base_week)
        self.spinBox_2.setValue(self.now_week)
        self.log.info(f'Year:{self.now_year}, Week:{self.now_week}')
        self.comboBox.setEnabled(False)

    def on_clear_logs(self):
        # 添加按钮点击动画
        self.textBrowser.clear()
        self.log.debug('-' * 20 + 'Cleaned' + '-' * 20)

    def select_input_directory(self):
        """选择输入目录的槽函数"""
        dir_path = QFileDialog.getExistingDirectory(
            self,
            "Select Input directory",  # 对话框标题
            "",  # 初始目录（空表示当前目录）
            QFileDialog.Option.ShowDirsOnly  # 只显示目录
        )

        if dir_path:  # 如果用户没有取消选择
            self.lineEdit.setText(dir_path)
        self.log.info(f"Selected input directory: {dir_path}")

    def select_output_directory(self):
        """选择输出目录的槽函数"""
        dir_path = QFileDialog.getExistingDirectory(
            self,
            "Select Output directory",
            self.lineEdit_2.text() or "",  # 默认显示当前已填路径
            QFileDialog.Option.DontResolveSymlinks
        )

        if dir_path:
            self.lineEdit_2.setText(dir_path)
        self.log.info(f"Selected output directory: {dir_path}")

    def update_controls_state(self):
        """根据comboBox选择更新控件状态"""
        # 获取当前选项索引
        current_index = self.comboBox.currentIndex()
        self.mode = current_index
        self.log.debug(f"Selected mode: {self.comboBox.currentText()}")
        # 判断逻辑
        # if current_index == 0:  # 第一个选项
        #     is_enabled = False
        # elif current_index == 1:  # 第二个选项
        #     is_enabled = True
        #
        # else:  # 其他选项（可选处理）
        #     is_enabled = True  # 默认启用
        #
        # # 设置控件状态
        # self.spinBox_2.setEnabled(is_enabled)

    def on_change_log_level(self, ):
        log_level_map = {
            0: logging.DEBUG,
            1: logging.INFO,
            2: logging.WARNING,
            3: logging.ERROR,
        }
        current_index = self.comboBox_2.currentIndex()
        log_level = log_level_map.get(current_index, logging.DEBUG)
        self.logger.set_level(log_level)

    def on_record_log(self, log_level, message):

        log_map = {
            'DEBUG': self.log.debug,
            'INFO': self.log.info,
            'WARNING': self.log.warning,
            'ERROR': self.log.error,
        }
        log_map.get(log_level, self.log.debug)(message)

    def update_progress(self):
        pass

    def check_input_files(self):
        """Check and list Excel files in the specified directory"""
        # Get directory path from lineEdit
        dir_path = self.lineEdit.text().strip()
        base_year = self.dateEdit.date().year()
        print(f"\n[DEBUG] 基准年份: {base_year}")
        # 确保 spinBox 和 spinBox_2 的值正确获取
        base_week = self.spinBox.value()
        comparison_week = self.spinBox_2.value()
        comparison_year = base_year if base_week < comparison_week else base_year + 1
        self.base_week = int(f'{base_year}{base_week:02d}')
        self.comparison_week = int(f'{comparison_year}{comparison_week:02d}')
        # Validate empty input
        if not dir_path:
            self.log.warning("Directory path cannot be empty!")
            QMessageBox.warning(self, "Input Error", "Directory path cannot be empty!")
            return

        # Create Path object
        target_dir = Path(dir_path)

        # Validate path existence
        if not target_dir.exists():
            self.log.error(f"Directory does not exist:\n{dir_path}")
            QMessageBox.critical(self, "Path Error",
                                 f"Directory does not exist:\n{dir_path}")
            return

        # Validate path type
        if not target_dir.is_dir():
            self.log.error(f"Path is not a directory:\n{dir_path}")
            QMessageBox.critical(self, "Type Error",
                                 f"Path is not a directory:\n{dir_path}")
            return

        try:
            # Get all Excel files (support common formats)
            excel_files = [
                f.name for f in target_dir.iterdir()
                if (
                        f.is_file() and
                        f.suffix.lower() in ('.xls', '.xlsx', '.xlsm') and
                        not f.name.startswith(('~', '.', '~$'))  # 排除三类文件：
                    # 1. Unix隐藏文件 (.example.xlsx)
                    # 2. Office临时文件 (~$example.xlsx)
                    # 3. 自动保存文件 (~example.xlsx)
                )
            ]

            # Prepare result output
            if excel_files:
                self.log.debug("Found Excel files 👇:\n")
                for file in excel_files:
                    # self.log.debug(file)
                    if not (len(file) >= 10 and file[:6].isdigit()):
                        self.log.warning(f"Invalid file name: {file}")
                    elif not (int(file[:4]) >= self.now_year and int(file[4:6]) < 54):
                        self.log.warning(f"Invalid file name: {file}")
                    else:
                        self.log.info(f"Valid file name: {file}")
                        self.data_map[int(file[:6])] = file
                self.log.debug(f"Data map: {self.data_map}")
                if self.data_map:
                    if self.base_week not in self.data_map.keys():
                        msg = f"The data for week {self.base_week} does not exist.Please select the correct base week!"
                        self.log.warning(msg)
                        QMessageBox.warning(self, "Input Error", msg)
                        return self.is_data_checked
                    elif self.comparison_week not in self.data_map.keys():
                        msg = (f"The data for week {self.comparison_week} does not exist."
                               f"Please select a correct comparison week!")
                        self.log.warning(msg)
                        QMessageBox.warning(self, "Input Error", msg)
                        return self.is_data_checked
                    last_week = max(self.data_map.keys())
                    self.is_data_checked = True
                    self.log.info(f"Last week: {last_week}({self.data_map[last_week]})")

            else:
                result = "No Excel files found in this directory"
                self.log.warning(result)

            # Update status bar
            self.statusBar().showMessage(f"Found {len(excel_files)} Excel files, "
                                         f"Valid files: {len(self.data_map)}.", 5000)

        except PermissionError:
            self.log.error(f"Cannot access directory:\n{dir_path}")
            QMessageBox.critical(self, "Permission Error",
                                 f"Cannot access directory:\n{dir_path}")
        return self.is_data_checked

    def start_process(self):

        if not self.is_data_checked:
            self.log.warning("Please check the input files first!")
            if not self.check_input_files():
                return
        try:
            para = {
                "mode": self.mode,
                "base_week": self.base_week,
                "comparison_week": self.comparison_week,
                "input_path": self.lineEdit.text(),
                "output_path": self.lineEdit_2.text(),
            }
            # self.log.debug(f"Parameters: {para}")
            print(f"\n[DEBUG] 参数: {para}")
            print(f"\n[DEBUG] data_map: {self.data_map}")
            self.current_thread = ProcessThread(self.data_map, para)
            # 定义 handle_finished 函数

            self.current_thread.finished.connect(self.handle_finished)
            self.current_thread.progress_updated.connect(self.update_progress)
            self.current_thread.log_updated.connect(self.on_record_log)
            self.current_thread.start()
            print("=== 开始调试执行 ===")
        except Exception as e:
            self.log.error(f'Error: {e}')
            self.log.debug(traceback.format_exc())
            QMessageBox.critical(self, "Error", f"Error: {e}")

    @staticmethod
    def handle_finished(code, msg):
        print(f"\n[DEBUG] 执行结果: {code}, {msg}")
        if code == 0:
            QMessageBox.information(None, "Success", msg)
        else:
            QMessageBox.critical(None, "Error", msg)


if __name__ == "__main__":
    app = QApplication([])
    app.setStyleSheet(load_stylesheet(qt_api="pyqt6", palette=LightPalette))
    app.setStyle("Fusion")
    window = MainWindow()
    window.show()
    app.exec()
